/**
 * @Project: ods
 * @Package com.yonghui.ods.service.impl
 * FileName：MongoBaseServiceImpl.java
 * Version：v1.0
 * date：2017年4月10日
 * Copyright © 2017 YH Financial Service All Rights Reserved
 */

package pers.rcl.common.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import pers.rcl.common.collection.MongoSequence;
import pers.rcl.common.constant.CommonConstants;

import java.util.List;
import java.util.Objects;

import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

/**
 * FileName: MongoBaseServiceImpl.java
 *
 * @author: Hubert
 * @version: v1.0
 * @create at: 2017年4月10日 下午6:15:26
 * @reviewer:
 * @review at:
 * <p>
 * Revision history: date author version content
 * ------------------------------------------------------------
 * 2017年4月10日 Hubert v1.0 XXXX
 * <p>
 * Copyright © 2017 YH Financial Service All Rights Reserved
 */
@Service
public class MongoBaseServiceImpl  {
    private Log log = LogFactory.getLog(MongoBaseServiceImpl.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    @Value("${spring.profiles.active}")
    private String springProfilesActive;

    /**
     * @Title: getNextSequence @Description: 获取下一个自增id值 @param
     * collectionName @return param @return int return type @throws
     */

    public int getNextSequence(String collectionName) {
        MongoSequence seq = mongoTemplate.findAndModify(query(where("_id").is(collectionName)),
                new Update().inc("seq", 1), options().upsert(true).returnNew(true), MongoSequence.class);
        return seq.getSeq();
    }

    public <T> T getLocalCacheDataForTest(Query query, Class<T> clazz) {
        if (!Objects.equals(CommonConstants.PROFILES_ACTIVE_PROD, springProfilesActive)) {

            query = query.with(Sort.by(new Sort.Order(Direction.DESC, "_id"))).limit(1);
            T element = mongoTemplate.findOne(query, clazz);
            if (element != null) {
                return element;
            }
        }
        return null;
    }
}
